const app = getApp();
const { httpServer } = app.globalData;
const getInfo = wx.getAccountInfoSync();
const envVersion = getInfo.miniProgram.envVersion;
const baseUrl = envVersion == "release" ? 'https://photo.visiondefender.cn' : 'https://photo.visiondefender.cn';
const { wxmlFn } = require('./view.js')


Page({
  /**
   * 页面的初始数据
   */
  onShareAppMessage() {
    return {
      title: 'picker-view',
      path: 'page/component/pages/picker-view/picker-view'
    }
  },
  data: {
    statusBarHeight: 20,
    navBarHeight: 66,
    navBarWidth: 97,

    switchChecked: false,
    aspectRatio: "square",
    pictureNum: "nine", // twelve
    defaultArr: [], // 默认列表
    twelveArr: [], // 十二宫格的数据
    defaultObj: {
      imgUrl: '',
      type: "",
      squareUrl: "",
      narrowUrl: "",
    },

    isTwelve: false,
    src: "",

    nameVal: "", // 姓名
    idVal: "", // 身份证
    ageVal: "", // 出生日期
    infoVal: "", // 附加信息
    dateVal: "", // 附加信息

    newUrl: "",
    dateEnd: new Date()
  },

  // 添加图片
  addPicture() {
    console.error(1)
    const { pictureNum, isTwelve, twelveArr } = this.data;
    if (isTwelve) {
      if (pictureNum == "nine") {
        this.setData({
          pictureNum: "twelve"
        })
      } else {
        this.setData({
          pictureNum: "nine"
        })
      }
    } else {
      wx.setStorageSync('isTwelve', true);
      wx.setStorageSync('twelveArr', twelveArr);
      wx.navigateTo({
        url: `/pages/photograph/photograph?position=position9&type=twelve&index=0&isEditor=1`,
      })
    }
  },

  // 添加元素
  addEl() {
    console.error(2)
    wx.setStorageSync('isTwelve', this.data.isTwelve);
    wx.navigateTo({
      url: '/pages/photograph/photograph?type=new',
    })
  },

  // 下载图片
  download() {
    const { nameVal, idVal, ageVal, infoVal, dateVal } = this.data;
    if (nameVal.trim() == '' && idVal.trim() == '' && ageVal.trim() == '' && infoVal.trim() == '' && dateVal.trim() == '') {
      wx.showToast({
        icon: "error",
        title: '请输入',
      })
      return;
    }

    wx.showLoading({
      title: '图片生成中',
      mask: true,
    })
    this.renderToCanvas(() => {
      wx.getSetting({
        success: (res) => {
          wx.hideLoading();
          if (!res.authSetting['scope.writePhotosAlbum']) {
            // 首次申请权限
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                this.downloadImage();
              },
              fail: () => this.showPermissionGuide()
            });
          } else {
            this.downloadImage(); // 已授权直接下载
          }
        }
      });
    });
  },

  downloadImage() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.src,
      success: () => {
        wx.showToast({ title: '保存成功', icon: 'success' });
      },
    });
  },

  // 拍照上传到 OSS 
  fileUpload () {
    const _this = this;
    let files = this.data.src;

    wx.uploadFile({
      url: baseUrl + "/api/common/upload",
      filePath: files,
      header: {
        "Content-Type": "multipart/form-data",
        token: wx.getStorageSync('userinfo').token
      },
      name: 'file',
      success (res){
        console.log(data, '上传成功')
        const data = JSON.parse(res.data);
        if (data.code != '1') {
          wx.showToast({
            icon: "none",
            title: '上传失败'
          });
        } else {
          _this.createInformation({
            fullurl: data.data.fullurl,
            url: data.data.url
          })
        }
      },
      fail (error) {
        console.log(error)
        wx.showToast({
          icon: "none",
          title: '上传失败'
        });
      },
      complete () {}
    })
  },

  // 保存数据
  async createInformation(urlObj) {
    const { nameVal, idVal, ageVal, infoVal, dateVal } = this.data;
    
    let result = await httpServer("post", "/api/Photo/createInformation", {
      name: nameVal,
      id_number: idVal,
      text: infoVal,
      date: dateVal,
      img: urlObj.fullurl,
      age: ageVal,
    })
    
    wx.reLaunch({
      url: `/pages/database/database`
    })
  },

  // 引导用户手动开启
  showPermissionGuide() {
    wx.showModal({
      title: '提示',
      content: '需要您授权保存到相册',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) wx.openSetting(); // 打开系统设置页
      }
    });
  },

  // 设置
  setting() {
    wx.navigateTo({
      url: '/pages/setting/setting',
    })
  },

  // 分享
  shared() {
    wx.showLoading({
      title: '图片生成中',
      mask: true,
    })
    this.renderToCanvas(() => {
      wx.hideLoading();
      wx.showShareImageMenu({
        path: this.data.src
      })
    });
  },

  // 保存
  save() {
    const { nameVal, idVal, ageVal, infoVal, dateVal } = this.data;
    if (nameVal.trim() == '' && idVal.trim() == '' && ageVal.trim() == '' && infoVal.trim() == '' && dateVal.trim() == '') {
      wx.showToast({
        icon: "error",
        title: '请输入',
      })
      return;
    }

    wx.showLoading({
      title: '图片生成中',
      mask: true,
    })
    this.renderToCanvas(() => {
      this.fileUpload();
    });
  },

  // 切换展示内容
  switchChange(e) {
    if (e.detail.value) {
      this.setData({
        aspectRatio: "narrow"
      })
    } else {
      this.setData({
        aspectRatio: "square"
      })
    }
  },

  // 选择拍照方式
  selectPhptp(e) {
    const dataset = e.currentTarget.dataset;
    const { index, item, type } = dataset;

    if (type) {
      if (item.type) {
        wx.setStorageSync('isTwelve', this.data.isTwelve);
        wx.setStorageSync('twelveArr', this.data.twelveArr);
        wx.navigateTo({
          url: `/pages/photograph/photograph?position=${ item.type }&index=${ index }&type=twelve`,
        })
      }
    } else {
      if (item.type) {
        wx.setStorageSync('isTwelve', this.data.isTwelve);
        wx.setStorageSync('defaultArr', this.data.defaultArr);
        wx.navigateTo({
          url: `/pages/photograph/photograph?position=${ item.type }&index=${ index }`,
        })
      }
    }
    
    console.log('选择拍照方式', index, item)
  },
  
  // 输入框赋值
  inputVoluation(value, type) {
    this.setData({
      [type]: value
    })
  },

  // 姓名输入框
  nameInput: function (e) {
    this.inputVoluation(e.detail.value, 'nameVal')
  },

  // 身份证输入框
  idInput: function (e) {
    this.inputVoluation(e.detail.value, 'idVal')
  },

  // 出生日期选择
  ageInput: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.inputVoluation(e.detail.value, 'ageVal')
  },

  // 日期选择
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.inputVoluation(e.detail.value, 'dateVal')
  },

  // 附加信息输入
  infoInput(e) {
    this.inputVoluation(e.detail.value, 'infoVal')
  },

  // 附加信息输入
  dateInput(e) {
    this.inputVoluation(e.detail.value, 'dateVal')
  },

  // 附加信息输入
  infoInput(e) {
    this.inputVoluation(e.detail.value, 'infoVal')
  },

  renderToCanvas(callback) {
    const { defaultArr, twelveArr, aspectRatio, pictureNum, nameVal, idVal, ageVal, infoVal, dateVal } = this.data;
    const { wxml, style } = wxmlFn(defaultArr, twelveArr, {
      nameVal, idVal, ageVal, infoVal, dateVal
    }, aspectRatio, pictureNum);
    this.widget.renderToCanvas({ wxml, style }).then(res => {
      this.container = res  // 保存布局信息
      this.extraImage(callback)     // 生成图片
    })
  },
  extraImage(callback) {
    this.widget.canvasToTempFilePath().then(res => {
      console.log(res.tempFilePath)
      this.setData({
        src: res.tempFilePath,  // 图片临时路径
      })

      setTimeout(() => {
        callback && callback()
      }, 100)
    })
  },

  timer() {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1; // 注意月份从0开始，所以要加1
    const date = today.getDate();
    return `${ year }-${ month }-${ date }`
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { navBarHeight, statusBarHeight, navBarWidth } = app.globalData.WindowInfo;
    const defaultArr = []
    const typeArr = [ "position8", "position1", "position2", "position7", "middle", "position3", "position6", "position5", "position4" ];
    for (let i = 0; i < typeArr.length; i++) {
      const defaultObj = JSON.parse(JSON.stringify(this.data.defaultObj));
      defaultObj.type = typeArr[i];
      defaultArr.push(defaultObj)
    }
    const twelveArr = []
    const twelveTypeArr = [ "position9", "", "position10" ];
    for (let i = 0; i < twelveTypeArr.length; i++) {
      const defaultObj = JSON.parse(JSON.stringify(this.data.defaultObj));
      defaultObj.type = twelveTypeArr[i];
      twelveArr.push(defaultObj)
    }

    this.setData({
      statusBarHeight,
      navBarHeight,
      navBarWidth,

      defaultArr,
      twelveArr,
      dateVal: this.timer()
    })

    this.widget = this.selectComponent('.widget')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const newUrl = wx.getStorageSync('newUrl');
    wx.removeStorageSync('newUrl');
    if (newUrl || newUrl == "") {
      this.setData({
        newUrl: newUrl,
      })
    }

    
    const isTwelve = wx.getStorageSync('isTwelve');
    wx.removeStorageSync('isTwelve');
    if (isTwelve) {
      this.setData({
        isTwelve
      })
    }

    const defaultArr = wx.getStorageSync('defaultArr');
    wx.removeStorageSync('defaultArr');

    if (defaultArr) {
      console.log("九宫格")
      this.setData({
        defaultArr
      })
    }

    const twelveArr = wx.getStorageSync('twelveArr');
    wx.removeStorageSync('twelveArr');
    if (twelveArr) {
      console.log("十二宫格")
      this.setData({
        twelveArr,
        pictureNum: "twelve"
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },
})